from django.http import Http404
from django.views.decorators.vary import vary_on_cookie
from nameremoved.comics.models import Comic
from nameremoved.helpers import render_with_requestcontext
from nameremoved.comics import present_image
import datetime

COOKIE_AGE = 31536000

def get_old_comic(which_comic):
    """
    Gets a comic of a particular number. This way I am not dealing with
    fenceposts EVERY SINGLE FREAKING TIME. Instead just once.
    """
    which = int(which_comic)
    if which > Comic.public_comics.count(): raise Http404
    return Comic.public_comics.all()[which-1]

def comic_context(which=None):
    """
    The context all the comic view templates want. which is an int
    """
    last = Comic.public_comics.count()
    if not which: which = last
    which_comic = get_old_comic(which)
    context = {
        'comic': which_comic,
        'id': which,
        'first': 1,
        'previous': which-1,
        'next': which+1,
        'last': last,
    }
    return context

def with_cookie(response,which_comic):
    """sets the saved cookie on a response"""
    expires=datetime.datetime.strftime(datetime.datetime.utcnow() + 
               datetime.timedelta(seconds=COOKIE_AGE), 
                "%a, %d-%b-%Y %H:%M:%S GMT")
    response.set_cookie(
        "saved_comic",
        which_comic,
        max_age = COOKIE_AGE,
        expires = expires,
        path = "/",
    )
    return response

# views begin here

@vary_on_cookie
def index(request):
    """the default comic view"""
    c = comic_context()

    new_visitor = "saved_comic" not in request.COOKIES
    
    try: saved_id = int(request.COOKIES["saved_comic"])
    except (ValueError, KeyError): saved_id = c["id"]
    
    c.update({
        'saved_id': saved_id,
        'saved': get_old_comic(saved_id),
        'new_visitor': new_visitor,
    })
    
    response = render_with_requestcontext('comics/front.html', c, request)
    return with_cookie(response, c["id"])

@vary_on_cookie
def comic(request, which_comic):
    """a page for a single comic in the past"""
    response = render_with_requestcontext('comics/single.html',
                                          comic_context(int(which_comic)),
                                          request)
    return with_cookie(response, which_comic)

def archive(request):
    """the archive page listing all viewable comics"""
    c = {
        'comics': Comic.public_comics.all(),
    }
    return render_with_requestcontext('comics/archive.html', c, request)

def comic_image(request, which_comic):
    """the image for a particular comic"""
    return present_image(get_old_comic(which_comic))
